import {ProCard} from '@ant-design/pro-components';
import {Button, message, Space} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {useEffect, useState} from 'react';
import CarouselCard from './components/CarouselCard';
import AddModal from './components/AddModal';
import {addCarousel, deleteCarousel, listCarousel, updateCarousel} from "@/pages/system/carousel/services";

export default () => {
  const [data, setData] = useState<API.Carousel[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentItem, setCurrentItem] = useState<API.Carousel | undefined>();
  const [action, setAction] = useState<'add' | 'edit'>('add');

  const loadData = async () => {
    setLoading(true);
    try {
      const {data} = await listCarousel({});
      setData(data || []);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleSubmit = async (values: API.Carousel) => {
    try {
      if (action === 'add') {
        const {data} = await addCarousel(values)
        if (data) {
          message.success('添加成功');
          setModalVisible(false);
          loadData();
        }
      } else if (action === 'edit') {
        const {data} = await updateCarousel(values)
        if (data) {
          message.success('修改成功');
          setModalVisible(false);
          loadData();
        }
      }
    } finally {
      setLoading(false);
    }
  }

  const handleDelete = async (id: number) => {
    const {data} = await deleteCarousel(id);
    if (data) {
      message.success('删除成功');
      loadData();
    }
  };

  return (
    <>
      <ProCard
        title="轮播图管理"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined/>}
            onClick={() => {
              setCurrentItem(undefined);
              setAction('add');
              setModalVisible(true);
            }}
          >
            添加轮播图
          </Button>
        }
      >
        <Space wrap size={16}>
          {data.map(item => (
            <CarouselCard
              key={item.id}
              data={item}
              onEdit={item => {
                setCurrentItem(item);
                setAction('edit');
                setModalVisible(true);
              }}
              onDelete={async () => {
                await handleDelete(item.id)
              }}
            />
          ))}
        </Space>
      </ProCard>

      <AddModal
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onSubmit={handleSubmit}
        initialValues={currentItem}
      />
    </>
  );
};
